#AES加解密
#调库：最初始，直接对文本加解密。
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64

class AESCipher:
    def __init__(self, key):
        # 确保密钥长度为16、24或32字节
        self.key = key.encode('utf-8').ljust(32)[:32]
        self.cipher = AES.new(self.key, AES.MODE_CBC)
    
    def encrypt(self, data):
        data = data.encode('utf-8')
        padded_data = pad(data, AES.block_size)
        iv = self.cipher.iv
        encrypted = self.cipher.encrypt(padded_data)
        return base64.b64encode(iv + encrypted).decode('utf-8')

    def decrypt(self, encrypted_data):
        encrypted_data = base64.b64decode(encrypted_data)
        iv = encrypted_data[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        decrypted = unpad(cipher.decrypt(encrypted_data[AES.block_size:]), AES.block_size)
        return decrypted.decode('utf-8')
